import { deleteTag, queryTagList } from "@/api/content/tag";
import { useState, useCallback, useEffect } from "react";
import { Tag } from "../../../../types/content/tag";
import { message } from "antd";

export const useTagList = () => {
    const [messageApi] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [searchForm, setSearchForm] = useState<Tag.Query>({
        name: "",
        remark: "",
    });
    const [pagination, setPagination] = useState<Pagination>({
        pageNo: 1,
        pageSize: 10,
        total: 0,
    });
    const [tableData, setTableData] = useState<Tag.Row[]>([]);
    /**
     * 获取标签列表
     */
    const getTagList = useCallback(async () => {
        setLoading(true);
        const params = {
            pageNo: pagination.pageNo,
            pageSize: pagination.pageSize,
            ...searchForm,
        };
        const res = await queryTagList(params);
        setLoading(false);
        if (res.code === 200) {
            setTableData(res.data.rows || []);
            setPagination({
                pageNo: pagination.pageNo,
                pageSize: pagination.pageSize,
                total: res.data.total,
            });
        }
    }, [pagination.pageNo, pagination.pageSize, searchForm]);
    const removeTag = async (id: string) => {
        const res = await deleteTag({
            ids: [id]
        })
        if (res.code == 200) {
            messageApi.success('删除成功!')
            if (tableData.length === 1) {
                setPagination({
                    pageNo: Math.max(1, pagination.pageNo - 1),
                    pageSize: pagination.pageSize,
                    total: pagination.total
                })
            } else {
                getTagList()
            }
        }
    }
    useEffect(() => {
        getTagList();
    }, [getTagList, searchForm]);
    return {
        setPagination,
        setSearchForm,
        pagination,
        loading,
        tableData,
        getTagList,
        removeTag
    }
}